package com.aiyun.rabbit.rabbitdemo.stock.service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.aiyun.rabbit.rabbitdemo.dto.OrderDTO;
import com.aiyun.rabbit.rabbitdemo.dto.OrderFailureDTO;
import com.aiyun.rabbit.rabbitdemo.dto.OrderStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static org.slf4j.LoggerFactory.getLogger;

@Service
public class StockReceiveService {

	private final Logger log = getLogger(StockReceiveService.class);
	@Autowired
	private RabbitTemplate rabbitTemplate;

	@RabbitListener(queues = "queue.stock.receive")
	public void stockReceive(String message) throws IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		OrderDTO orderDTO = objectMapper.readValue(message.getBytes(StandardCharsets.UTF_8), OrderDTO.class);
		log.info("接收到待处理订单，订单信息是:[{}]", orderDTO);
		orderDTO.setOrderStatus(OrderStatus.STOCK_CONFIRMED);
		if (orderDTO.getSuccess() == null || orderDTO.getSuccess()) {
			rabbitTemplate.convertAndSend(
					"exchange.order",
					"confirm",
					objectMapper.writeValueAsString(orderDTO)
			);
			log.info("仓库服务订单信息已经确认，等待订单服务处理");
		} else{
			// 模拟订单失败情况
			OrderFailureDTO orderFailureDTO = objectMapper.readValue(objectMapper.writeValueAsString(orderDTO), OrderFailureDTO.class);
			orderFailureDTO.setFailureMessage("仓库处理失败");
			rabbitTemplate.convertAndSend(
					"exchange.order.process.failure",
					"",
					objectMapper.writeValueAsString(orderFailureDTO)
			);
		}
	}

	@RabbitListener(queues = "queue.stock.process.failure")
	public void orderFailureProcess(String message){
		log.error("仓库服务收到订单失败信息，该订单是：[{}]", message);
	}
}
